package com.ilxqx.framework.rc;

import com.ilxqx.framework.util.DbUtils;
import com.ilxqx.framework.util.SqlFileExecutionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 初始化Quartz定时计划任务
 * @author venus
 */
@Component
@Slf4j
public class InitQuartzTables implements CommandLineRunner {

    /**
     * quartz的表数目
     */
    private static final int QUARTZ_TABLE_NUM = 11;

    /**
     * SQL文件配置
     */
    @Value("${spring.quartz.jdbc.schema}")
    private String sqlPath;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        // 判断quartz相关的表是否存在
        List<Map<String, Object>> results = DbUtils.query("show tables like 'QRTZ_%';");
        if (results.size() != QUARTZ_TABLE_NUM) {
            // quartz表不全或者没有，执行sql，创建表
            String path = StringUtils.removeStart(this.sqlPath, "classpath:");
            File sqlFile = SqlFileExecutionUtils.getFileFromClassPath(path);
            // 执行
            log.info("检测到Quartz定时计划任务表结构不完整，正在重新创建...");
            SqlFileExecutionUtils.executeSqlFile(sqlFile);
            log.info("Quartz表结构创建完毕");
        }
    }

}
